package com.github.lee.unsplash.ui.search

import android.content.Context
import android.graphics.Color
import android.text.TextUtils
import android.view.Menu
import android.view.MenuItem
import androidx.activity.viewModels
import androidx.annotation.Nullable
import androidx.appcompat.widget.Toolbar
import androidx.core.app.ActivityOptionsCompat
import androidx.core.view.get
import com.github.lee.core.common.normalIntent
import com.github.lee.mvvm.core.ui.BaseActivity
import com.github.lee.unsplash.R
import com.github.lee.unsplash.databinding.SearchActivityBinding
import com.github.lee.unsplash.databinding.ToolbarSearchBinding
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class SearchActivity : BaseActivity<SearchActivityBinding, SearchVM>() {

    private val toolbar by lazy {
        ToolbarSearchBinding.inflate(layoutInflater)
            .also {
                it.backClick = {
                    onBackPressed()
                }
            }
    }

    //===Desc:=========================================================


    companion object {
        fun start(context: Context, @Nullable options: ActivityOptionsCompat? = null) {
            context.startActivity(
                normalIntent(context, SearchActivity::class.java),
                options?.toBundle()
            )
        }
    }

    //===Desc:=========================================================

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_search, menu)
        menu?.get(0)?.title = if (TextUtils.isEmpty(pageVM.userInput.get())) {
            getString(R.string.xpopup_cancel)
        } else {
            getString(R.string.txt_clean_input)
        }
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.cancel_action -> {
                if (TextUtils.isEmpty(pageVM.userInput.get())) {
                    onBackPressed()
                } else {
                    pageVM.userInput.set("")
                }
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onCreateViewModel(): SearchVM = viewModels<SearchVM>().value


    override fun onCreateToolbar(): Toolbar {
        return toolbar
            .tlSearch
    }

    override fun onCreateSuccess(): SearchActivityBinding =
        SearchActivityBinding.inflate(layoutInflater)

    //===Desc:=========================================================

    override fun onSetViewListener() {
        super.onSetViewListener()
        toolbar.textChanged = {
            invalidateOptionsMenu()
        }
    }

    override fun onSetViewData() {
        super.onSetViewData()
        setStatusBarColor(Color.WHITE)
        changeStatusBarTextColor(true)

        toolbar.vm = pageVM

    }

}